package com.heima.wemedia.service.impl;

import com.github.pagehelper.PageHelper;
import com.heima.file.MinIOTemplate;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.dtos.WmMaterialDto;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.entity.WmMaterial;
import com.heima.model.wemedia.entity.WmNewsMaterial;
import com.heima.wemedia.dao.WmMaterialDao;
import com.heima.wemedia.dao.WmNewsMaterialDao;
import com.heima.wemedia.service.WmMaterialService;
import com.heima.wemedia.util.WmThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * 自媒体素材表(WmMaterial)表服务实现类
 *
 * @author makejava
 * @since 2022-04-10 17:12:53
 */
@Service("wmMaterialService")
public class WmMaterialServiceImpl implements WmMaterialService {
    @Resource
    private WmMaterialDao wmMaterialDao;

    @Autowired
    private MinIOTemplate minIOTemplate;

    @Autowired
    private WmNewsMaterialDao wmNewsMaterialDao;


    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     */
    @Override
    public WmMaterial queryById(Long id) {
        return this.wmMaterialDao.queryById(id);
    }

    /**
     * 分页查询
     *
     * @param wmMaterial  筛选条件
     * @param pageRequest 分页对象
     * @return 查询结果
     */
    @Override
    public Page<WmMaterial> queryByPage(WmMaterial wmMaterial, PageRequest pageRequest) {
        long total = this.wmMaterialDao.count(wmMaterial);
        return new PageImpl<>(this.wmMaterialDao.queryAllByLimit(wmMaterial, pageRequest), pageRequest, total);
    }

    /**
     * 新增数据
     *
     * @param wmMaterial 实例对象
     * @return 实例对象
     */
    @Override
    public WmMaterial insert(WmMaterial wmMaterial) {
        this.wmMaterialDao.insert(wmMaterial);
        return wmMaterial;
    }

    /**
     * 修改数据
     *
     * @param wmMaterial 实例对象
     * @return 实例对象
     */
    @Override
    public WmMaterial update(WmMaterial wmMaterial) {
        this.wmMaterialDao.update(wmMaterial);
        return this.queryById(wmMaterial.getId());
    }

    /**
     * 通过主键删除数据
     *
     * @param id 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById(Long id) {
        return this.wmMaterialDao.deleteById(id) > 0;
    }

    /**
     * 图片上传
     *
     * @param multipartFile
     */
    @Override
    public ResponseResult upload(MultipartFile multipartFile) throws IOException {

        long size = multipartFile.getSize();
        if (size <= 0 || multipartFile == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }

        //1 把图片信息存储在素材表中
        String originalFilename = multipartFile.getOriginalFilename();
        //获取一个uuid字符串
        String fileName = UUID.randomUUID().toString().replace("-", "");
        //获取文件后缀
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        //拼接成新的文件名,防止文件同名
        fileName = fileName + suffix;

        //2 把图片信息保存在minio中
        String realPath = minIOTemplate.uploadImgFile("", fileName, multipartFile.getInputStream());

        WmMaterial wmMaterial = new WmMaterial();
        wmMaterial.setUserId(WmThreadLocalUtil.get().getId());
        wmMaterial.setCreatedTime(new Date());
        wmMaterial.setUrl(realPath);
        wmMaterial.setType(0);
        wmMaterial.setIsCollection(0);
        wmMaterial.setUpdatedTime(new Date());
        wmMaterialDao.insert(wmMaterial);
        return ResponseResult.okResult(wmMaterial);
    }


    /**
     * 分页查询图片
     *
     * @param wmMaterialDto
     * @return
     */
    @Override
    public ResponseResult list(WmMaterialDto dto) {

        if (dto == null) {
            return new ResponseResult(500, AppHttpCodeEnum.PARAM_REQUIRE);
        }
        //如果未点分页,执行默认分页
        dto.checkParam();

        //构造分页条件
        WmMaterial wmMaterial = new WmMaterial();

        wmMaterial.setUserId(WmThreadLocalUtil.get().getId());

        Short isCollection = dto.getIsCollection();
        //判断是否需要查询已收藏的图片
        if (isCollection != null && isCollection == 1) {
            wmMaterial.setIsCollection(Integer.valueOf(isCollection));
        }
        //开启分页查询
        PageHelper.startPage(dto.getPage(), dto.getSize());
        com.github.pagehelper.Page<WmMaterial> page = wmMaterialDao.queryAll(wmMaterial);

        ResponseResult result = new PageResponseResult(dto.getPage(), dto.getSize(), (int) (page.getTotal()));

        result.setData(page.getResult());

        return result;
    }

    @Override
    public ResponseResult collect(Integer id) {


        WmMaterial wmMaterial = this.queryById(Long.valueOf(id));
        //1 代表已收藏
        wmMaterial.setIsCollection(1);

        this.update(wmMaterial);
        return  ResponseResult.errorResult(200,"操作成功");
    }

    @Override
    public ResponseResult cancelCollect(Integer id) {


        WmMaterial wmMaterial = this.queryById(Long.valueOf(id));
        //1 代表已收藏
        wmMaterial.setIsCollection(0);

        this.update(wmMaterial);
        return  ResponseResult.errorResult(200,"操作成功");
    }


    /**
     * 删除无效素材
     * @param id
     * @return
     */
    @Override
    public ResponseResult del(Integer id) {

        WmMaterial wmMaterial = wmMaterialDao.queryById(Long.valueOf(id));
        if(wmMaterial==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }

        //判断该素材是否已被文章引用
       List<WmNewsMaterial> wmNewsMaterialList= wmNewsMaterialDao.queryByMaterialId(id);
        if(wmNewsMaterialList.size()>0){
            return ResponseResult.errorResult(AppHttpCodeEnum.NO_OPERATOR_AUTH);
        }

        wmMaterialDao.deleteById(Long.valueOf(id));
        return ResponseResult.okResult("删除成功");
    }
}
